<?php
// +----------------------------------------------------------------------
// | Description: 消费计算公式（算法） - BillMath
// +----------------------------------------------------------------------
// | Author: liaoyizhi <liaoyizhi@gmail.com>
// +----------------------------------------------------------------------
// | Update: Markus <i@yoyoyo.me>
// +----------------------------------------------------------------------

namespace codelord\finance\model;

use think\Model;

class BillMath extends Model {
    /**
     * 根据bill_type_id获取涉及到的算法
     * @param int $id   算法类型ID
     * @return null|array
     */
    public function getMathByTypeId(int $id) : ? array
    {
        $result = $this->where(['bill_type_id' => $id])->select();
        // 为了兼容tp5.0和5.1，先判断返回的是数据集对象还是数组
        if (is_object($result)) {
            return $result->toArray();
        }
        return $result;
    }

    /**
     * 根据算法，处理货币符号
     * @param array $currency_data 各种货币消费组装数组
     * @param array $allmath       相关的消费算法数组
     * @return array
     */
    public function getCurrencyMath(array $currency_data,array $allmath) : array
    {
        $new_currency_data = [];
        $new_currency_data['uid'] = $currency_data['uid'];
        $new_currency_data['currency'] = [];
        foreach ($allmath as $math) {
            if (array_key_exists($math['currency_index'], $currency_data['currency'])) {
                $currency = $currency_data['currency'][$math['currency_index']];
                $math_rule = explode(',', $math['math']);
                $reason = isset($currency[3]) && !empty($currency[3]) ? $currency[3] : $math['remark'];
                $new_currency_data['currency'][$math['currency_index']] = [
                    $currency[0],
                    $currency[1] * $math_rule[0],
                    $currency[2] * $math_rule[1],
                    $reason
                ];
            }
        }
        return $new_currency_data;
    }
}
